<template>
  <div class="app-container">
    <el-form
      ref="userForm"
      :model="userForm"
      :rules="rules"
      label-width="80px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item
            label="用户名"
            prop="nick_name">
            <el-input
              v-model="userForm.nick_name"
              placeholder="用户名"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="账号"
            prop="name">
            <el-input
              v-model="userForm.name"
              placeholder="账号"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="角色"
            prop="roles">
            <el-select
              style="width:100%;"
              v-model="userForm.roles"
              placeholder="请选择角色">
              <el-option
                v-for="( role,index) in roleListOptions"
                :key="index"
                :label="role.label"
                :value="role.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>
<script>
import CryptoJS from 'crypto-js';
import { save, getDetail } from '@/api/user';
import { roleListOptions } from "@/data/user";
export default {
  name: 'add',
  props: {
    userId: {
      type: [String, Number],
      default: 0,
    },
  },
  data() {
    return {
      userForm: {
        nick_name: '',
        name: '',
        roles:'normal'
      },
      rules: {
        nick_name: [{ required: true, trigger: 'blur', message: '用户昵称不能为空' }],
        name: [
          { required: true, trigger: 'blur', message: '账号不能为空' },
          { pattern: /^1[3456789]\d{9}$/, message: '账号必须为手机号码', trigger: 'blur' },
        ],
        roles: [{ required: true, trigger: 'blur', message: '请选择角色' }],
      },
      roleListOptions,
    };
  },
  watch:{
    userId:{
      handler(value){
        this.getUserDetail(value)
      },
      immediate: true
    }
  },
  methods: {
    handleSubmit() {
      this.$refs.userForm.validate(valid => {
        if (valid) {
          this.$emit('update:loadingButton', ['submit']);
          let params = { ...this.userForm };
          save(params).then(res => {
            if( typeof params.id != 'undefined' ){
              this.$message.success(res.message)
            } else {
              this.$message({
                message:res.message, 
                type:'success',
                duration:10000
              });
            }
            this.$emit('update:loadingButton', []);
            this.$emit('update:visible', false);
          });
        }
      });
    },
    getUserDetail(value){
      if(value > 0){
        getDetail({ id: value }).then(res=>{
          this.$set( this, 'userForm', res.data )
        })
      }
    }
  },
};
</script>
